package com.zcsy.manage.service.system.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.Role;
import com.zcsy.manage.model.system.RoleCell;
import com.zcsy.manage.model.system.RoleMenu;
import com.zcsy.manage.model.system.RoleUser;
import com.zcsy.manage.persistence.system.MenuDao;
import com.zcsy.manage.persistence.system.RoleCellDao;
import com.zcsy.manage.persistence.system.RoleDao;
import com.zcsy.manage.persistence.system.UserDao;
import com.zcsy.manage.service.common.CommonService;
import com.zcsy.manage.service.system.IRoleService;

/**
 * @Title: RoleServiceImpl.java
 * @Package： com.zcsy.shop.service.impl 
 * @Description: 角色类接口实现类
 *
 * @author tanghan barbadosliy@163.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2015年7月7日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Service
public class RoleServiceImpl extends SystemComService implements IRoleService {

	private static final String ZERO = "0";//造的假数据
	
    @Autowired
    private RoleDao roleDao;

    @Autowired
    private MenuDao menuDao;
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private RoleCellDao roleCellDao;
    
    @Override
    public List<Role> getAll() {
        return roleDao.getAll();
    }
    
    @Override
    public List<Role> getRoles(Integer type , String name) {
    	HashMap<String, Object> map = new HashMap<String, Object>();
    	map.put("type", type);
    	map.put("name", name);
    	List<Role> roles = roleDao.getRoles(map);
    	//非平台运营类型的角色需要获取对应小区信息
    	if(type != Constants.ADMIN_TYPE){
    		for(Role item : roles){
    			List<String>  roleId = new ArrayList<String>();
    			roleId.add(item.getId());
    			item.setCells(roleDao.getCellInfosByRoleId(roleId));
    		}
    	}
    	
        return roles;
    }

    @Override
    public int insert(Role record) {
        return roleDao.insert(record);
    }

    @Override
    public int updateByPrimaryKey(Role record) {
    	Role oldRole = roleDao.getRole(record.getId());
    	
    	oldRole.setRoleName(record.getRoleName());
    	oldRole.setDescrip(record.getDescrip());
    	oldRole.setRoleType(record.getRoleType());
    	oldRole.setIsAllCell(record.getIsAllCell());
    	
        return roleDao.updateByPrimaryKey(oldRole);
    }

    @Override
    public void updateRoleMenu(String roleId, String[] menus) {
        /**
         * 如果不管menus是否为空，均先清空权限
         */
        roleDao.deleteRoleMenus(roleId);
        if(menus != null && menus.length > 0) {
            for(String menuId : menus){
            	if(!menuId.equals(ZERO)){
            		RoleMenu roleMenu = new RoleMenu();
                    roleMenu.setMenuId(menuId);
                    roleMenu.setRoleId(roleId);
                    roleMenu.setId(UniqueNumberUtils.get18UniqueNumber());
                    roleDao.insertRoleMenu(roleMenu);
            	}
            }
        }
    }

    @Override
    public Menu getEnterUrlByRoleId(String roleId) {
        Menu parentMenu = roleDao.getHeaderMenuByRoleId(roleId);
        if(parentMenu!=null){
        	return getSubAvailableMenu(parentMenu.getId(), roleId);
        }else{
            return null;
        }
        
    }
    
    private Menu getSubAvailableMenu(String pid , String roleId){
    	Map<String , Object> map = new HashMap<String , Object>();
    	map.put("pid", pid);
	    map.put("roleId", roleId);
        List<Menu> subs = menuDao.getMenuByPIdAndRole(map);
        for(Menu item : subs){
        	Map<String , Object> mapItem = new HashMap<String , Object>();
        	mapItem.put("pid", item.getId());
        	mapItem.put("roleId", roleId);
            int itemsubsCount = menuDao.getSubMenuCountAndRole(mapItem);
            
            if(itemsubsCount > 0){
            	return getSubAvailableMenu(item.getId(), roleId);
            }
            
            return item;
        }
        return null;
    }

	@Override
	public Role getRole(String roleId) {
		return roleDao.getRole(roleId);
	}

	@Override
	public int deleteRoleMenus(String roleId) {
		return roleDao.deleteRoleMenus(roleId);
	}
	
	@Override
	public int deleteRoleCells(String roleId) {
		return roleDao.deleteRoleCells(roleId);
	}

	@Override
	public int deleteByPrimaryKey(String roleId) {
		return roleDao.deleteByPrimaryKey(roleId);
	}

	@Override
	public void updateRoleCell(String roleId,String[] cells) {
		
			roleDao.delRoleCell(roleId);
			if(cells != null && cells.length > 0) {
				for(String cellId : cells){
					if(!cellId.equals(ZERO)){
						RoleCell roleCell = new RoleCell();
						roleCell.setCellId(cellId);
						roleCell.setRoleId(roleId);
						roleCell.setId(UniqueNumberUtils.get18UniqueNumber());
						roleDao.insertRoleCell(roleCell);
					}
				}
			}
	}

	@Override
	public List<String> getCellIdListByRoleId(String roleId) {
		return roleDao.getCellIdListByRoleId(roleId);
	}
	
	@Override
	public List<CellInfo> getCellInfosByRoleId(List<String> list) {
		return roleDao.getCellInfosByRoleId(list);
	}

	@Override
	public List<Role> getRoleList(int type,String keyword) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("type", type);
		map.put("keyword", keyword);
		return roleDao.getRoleList(map);
	}

	@Override
	public List<String> getMenuLeafIdList(String roleId , int system) {
		HashMap<String , Object> map = new HashMap<String , Object>();
		map.put("roleId", roleId);
		map.put("system", system);
		return roleDao.getMenuLeafIdList(map);
	}

	@Override
	public List<String> getRoleListBycellId(String cellId, String userId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cellId", cellId);
		map.put("userId", userId);
		return roleDao.getRoleListBycellId(map);
	}
	
	@Override
	public List<String> getRoleListByPermissioncellId(String []cellId,List<String> roleId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cellId", cellId);
		map.put("roleId", roleId);
		return roleDao.getRoleListByPermissioncellId(map);
	}
	
	@Override
	public boolean checkIfRolePermission(String roleId){
		Role record = getRole(roleId);
    	List<String> list = new ArrayList<String>();
    	list.add(roleId);
    	record.setCells(getCellInfosByRoleId(list));
    	record.setMenus(menuDao.queryFunctionsByRoleId(roleId));
    	
    	int system = Constants.getFunctionFromUserType(record.getRoleType());
    	if(system == Constants.SYSTEM_OPERATION_WEB){
    		List<Menu> permissionMenu;//用户在角色这些小区的菜单集合
        	if(CommonService.getSessionUser().getUserType() != Constants.ADMIN_TYPE){
        		//取出覆盖所选小区权限的用户角色,然后再取这些角色下的菜单并集
        		String [] cellids = new String[record.getCells().size()];
        		for(int i = 0 ; i < record.getCells().size() ; i ++){
        			cellids[i] = record.getCells().get(i).getId();
        		}
        		List<String> permissionRoles = getRoleListByPermissioncellId(cellids, CommonService.getSessionUser().getRoleList());
        		if(CollectionUtils.isEmpty(permissionRoles)){
        			return false;
        		}
        		
        		HashMap<String , Object> map = new HashMap<String , Object>();
        	    map.put("roleIds", permissionRoles);
        	    map.put("system", system);
        	    permissionMenu =  menuDao.queryMenuByRoleIds(map);
        	}else{
        		//平台运营用户，直接取功能并集
        		HashMap<String , Object> map = new HashMap<String , Object>();
        	    map.put("roleIds", CommonService.getSessionUser().getRoleList());
        	    map.put("system", system);
        	    permissionMenu =  menuDao.queryMenuByRoleIds(map);
        	}
        	
        	//角色对应的菜单集合，有一个用户没有就无权限返回false
        	for(Menu item : record.getMenus()){
        		boolean have = false;
        		for(Menu j : permissionMenu){
            		if(item.getId().equals(j.getId())){
            			have = true;
            			break;
            		}
            	}
        		
        		if(!have){
        			return false;
        		}
        	}
        }else{//其他平台，只验证小区
        	List<CellInfo> userCell = CommonService.getSessionUser().getCellInfos();
            
            for(CellInfo item : record.getCells()){
            	//当前用户自己有权限的小区才可选中
            	boolean have = false;
            	for(CellInfo j : userCell){
            		if(item.getId().equals(j.getId())){
            			have = true;
            			break;
            		}
            	}
            	
            	if(!have){
        			return false;
        		}
            }
        }
    	
    	return true;
	}
	
	
	/** 
     * @Title: ifCurrAdmin 
     * @Description: 判断当前用户是否为超级管理员
     * @param @return     
     * @return boolean     
     * @throws 
     */
	@Override
    public boolean ifCurrAdmin(){
    	boolean isAdmin = false;
        List<String> currUserList = CommonService.getSessionUser().getRoleList();
        for(String item : currUserList){
        	if(Constants.SYS_ADMIN_ID.equals(item)){
        		isAdmin = true;
        		break;
        	}
        }
        
        return isAdmin;
    }
	
	/**
     * @Description 根据userId取对应的roleId<br>
     * 
     * @param userId 用户id
     * @return 
     * @author yangfan
     * @date 2016年9月7日
     * @see 
     */
    public List<RoleUser> getRoleIdByUserId(String userId) {
        return roleDao.getRoleIdByUserId(userId);
        
    }

	@Override
	public Integer selectCountByCellId(String cellId) {
		return roleCellDao.selectCountByCellId(cellId);
	}

	@Override
	public Integer selectCountByCompanyId(String[] companyIds, int userType) {
		return roleDao.selectCountByCompanyId(companyIds, userType);
	}
}
